import InterceptorInvoker.scope
import jdk.nashorn.internal.objects.Global
import kotlinx.coroutines.*
import java.util.*
import java.util.concurrent.*
import javax.xml.bind.JAXBElement
import kotlin.concurrent.thread

object InterceptorInvoker {

    //拦截器指针
    var mInterceptorPointer: Int = 0

    //拦截器队列
    private val mInterceptorQueue: LinkedList<Interceptor> = LinkedList()

    //本次流程处理结果
    var mResult = false
    var mMsg = ""

    //协程调配线程
    private val dispatch:CoroutineDispatcher=Dispatchers.Default
    //主线程Scope
    var scope=CoroutineScope(Job()+dispatch)


    /**
     * 初始化公共参数
     */
    private fun init() {
        //todo 初始化公共参数
    }

    /**
     * 输出运行结果
     * 输出公共参数
     * 释放资源并结束
     */
    private fun release(callback: CallBack) {
        callback.onResult()
        //todo 释放其他资源
    }


    /**
     * 添加拦截器
     */
    fun next(iterator: Interceptor): InterceptorInvoker {
        mInterceptorQueue.add(iterator)
        return this
    }

    /**
     * 添加一组拦截器
     */
    fun setInterceptors(list: List<Interceptor>): InterceptorInvoker {
        mInterceptorQueue.addAll(list)
        return this
    }


    /**
     * 按顺序执行拦截器
     * 遇到执行失败就结束
     */
    fun invoke(callback: CallBack) {
        init()
        println("thread:${Thread.currentThread().id}")

        InterceptorInvoker.scope.launch() {

            println("thread:${Thread.currentThread().id}")
                //拦截器为空,说明执行完成,返回结果
                if (mInterceptorQueue.isEmpty()) {
                    release(callback)
                    return@launch
                }
                val iterator = mInterceptorQueue.poll()
                //如果获取的拦截器为null,立即结束流程
                if (iterator == null) {
                    mResult = false
                    mMsg = "当前拦截器$mInterceptorPointer:null,流程异常结束"
                    release(callback)
                    return@launch
                }
                mInterceptorPointer++
                //执行拦截器
                iterator.init()
                iterator.execute()
                iterator.release()
                //保存拦截器运行结果
                mResult = iterator.mResult
                mMsg = iterator.mMsg
                //回到流程统一处理
                when {
                    //本流程执行成功,继续执行
                    iterator.mResult -> {
                        iterator.mCallBack.onSuccess()
                        invoke(callback)
                    }
                    //本拦截器执行失败,结束
                    !iterator.mResult -> {
                        iterator.mCallBack.onFail()
                        release(callback)
                        return@launch
                    }
                }
            }
}




    interface CallBack {
    fun onResult()
}

}